package com.spit.hkpost.ui.frg

import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.widget.ArrayAdapter
import androidx.fragment.app.activityViewModels
import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.Observer
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.StringUtils
import com.blankj.utilcode.util.ThreadUtils
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.spit.hkpost.R
import com.spit.hkpost.base.BaseFragment
import com.spit.hkpost.bean.DataBean
import com.spit.hkpost.databinding.FSearchRfidBinding
import com.spit.hkpost.ext.showToast
import com.spit.hkpost.util.MusicUtils
import com.spit.hkpost.util.ShellTokenizer
import com.spit.hkpost.viewmodel.RfidModel
import com.spit.hkpost.viewmodel.SearchRfidModel
import me.hgj.jetpackmvvm.ext.nav


/**
 * User: Nike
 *  2023/12/19 16:14
 */
class SearchRfidFrg : BaseFragment<SearchRfidModel, FSearchRfidBinding>() {

    var LabelTag: String? = null

    val rfidModel: RfidModel by activityViewModels()

    val mHandler = Handler(Looper.getMainLooper())


    override fun initView(savedInstanceState: Bundle?) {
        arguments?.let {
            LabelTag = it.getString("epc")
            var list = it.getString("list")
            val findAll: List<DataBean> = Gson().fromJson(list, object : TypeToken<List<DataBean>>() {}.type)
            findAll.forEach { dataBean ->
                dataBean.tagId?.let { tagId ->
                    mViewModel.listBean.add(tagId)
                }
            }
            //获取字符串数组
            val adpter = ArrayAdapter(requireContext(), android.R.layout.simple_spinner_item, mViewModel.listBean)
            mDatabind.etText.setTokenizer(ShellTokenizer(requireContext(), ' ', true))
            mDatabind.etText.setAdapter(adpter)
        }
        mDatabind.viewmodel = mViewModel
        mDatabind.click = ProxyClick()
        mViewModel.openStatus.set(getString(R.string.rfid_on))
        mViewModel.epc.set(if (StringUtils.isEmpty(LabelTag)) "" else LabelTag)
        MusicUtils.init(activity)

        lifecycle.addObserver(object : DefaultLifecycleObserver {
            override fun onPause(owner: LifecycleOwner) {
                super.onPause(owner)
                stop()
            }

            override fun onDestroy(owner: LifecycleOwner) {
                super.onDestroy(owner)
                rfidModel.isSearchOpen.value = null
                rfidModel.epcSearchData.value = null
                mHandler.removeCallbacksAndMessages(null)
            }
        })
    }

    override fun createObserver() {
        super.createObserver()
        rfidModel.epcSearchData.observe(viewLifecycleOwner, Observer {
            val s = mViewModel.epc.get()
            if (it == null || !mViewModel.epc.get().trim().equals(it.tagId))return@Observer
            var rssi = it.rssi?.replace("-", "")!!.toDouble()

            mHandler.removeCallbacks(delayTask)
            ThreadUtils.runOnUiThread {
                mDatabind.scSignal.setRssi(rssi.toInt())

                var rssi = rssi.toInt()
                when {
                    rssi in 1..35 -> {
                        MusicUtils.setPlayCount(3)
                        MusicUtils.setSpeechRate(2.0f)
                    }
                    rssi in 36..49 -> {
                        MusicUtils.setPlayCount(2)
                        MusicUtils.setSpeechRate(1.5f)
                    }
                    /*rssi in 50..59 -> {

                    }
                    rssi in 60..69 -> {

                    }
                    rssi > 70 -> {

                    }*/
                    else -> {
                        MusicUtils.setPlayCount(1)
                        MusicUtils.setSpeechRate(1.0f)
                    }
                }
                MusicUtils.play()
                mHandler.postDelayed(delayTask, 2000)
            }
        })
    }

    // 定义一个延迟任务的 Runnable
    val delayTask = Runnable {
        mDatabind.scSignal.setRssi(0)
    }

    inner class ProxyClick() {

        fun onClose(){
            nav().navigateUp()
        }

        fun onIsOpen(){
            if (StringUtils.isEmpty(mViewModel.epc.get())){
                showToast("No EPC")
                return
            }
            mViewModel.distance.set(getString(R.string.distance) + "：" + "0m")
            if (mViewModel.openStatus.get().equals(getString(R.string.rfid_on))){
                rfidModel.isSearchOpen.value = mViewModel.epc.get()!!.trim()
                mViewModel.openStatus.set(getString(R.string.rfid_off))
                mDatabind.etText.setEnabled(false);
            }else{
                stop()
            }
        }
    }

    private fun stop() {
        rfidModel.isSearchOpen.value = null
        mViewModel.openStatus.set(getString(R.string.rfid_on))
        mDatabind.etText.setEnabled(true);
    }

}


